package com.scau.yangsuiyu.estore.controller.buyer;

import com.scau.yangsuiyu.estore.controller.myComponent.TopSpan;
import com.scau.yangsuiyu.estore.dababases.entity.*;
import com.scau.yangsuiyu.estore.service.AppService;
import com.scau.yangsuiyu.estore.service.CartService;
import com.scau.yangsuiyu.estore.util.ImageViewUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author suiyu_yang
 * @description 购买商品的界面
 * @date 2019-06-11 11:17
 * @email suiyu_yang@163.com
 */
public class BuyGoodsPane extends AnchorPane implements Initializable {
    private Goods goods;
    private Shop shop;
    private TopSpan topSpan;

    @FXML
    private AnchorPane topSpanContainer;

    @FXML
    private ImageView mainImageView;

    @FXML
    private HBox imagesHBox;

    @FXML
    private Label priceLabel;

    @FXML
    private Label promotionalPriceLabel;

    @FXML
    private Label goodsNameLabel;

    @FXML
    private TextField goodsNumTF;

    @FXML
    private Label shopNameLabel;

    @FXML
    private Label sellerNameLabel;

    @FXML
    private Label quantityScoreLabel;

    @FXML
    private Label serviceScoreLabel;

    @FXML
    private Label deliveryScoreLabel;

    @FXML
    private Label goodsProfileLabel;

    @FXML
    private Label salesLabel;

    @FXML
    private Label inventoryLabel;


    public BuyGoodsPane(User user, Goods goods) {
        this.goods = goods;
        this.shop = goods.getShop();
        this.topSpan = new TopSpan(user);
        loadFXML();
    }

    private void loadFXML() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/buyer/BuyGoodsPane.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void plus() {
        int num = Integer.parseInt(goodsNumTF.getText());
        num++;
        if (num < goods.getInventory()) {
            goodsNumTF.setText(num + "");
        } else {
            goodsNumTF.setText(goods.getInventory() + "");
        }
    }

    @FXML
    private void minus() {
        int num = Integer.parseInt(goodsNumTF.getText());
        num--;
        if (num > 0) {
            goodsNumTF.setText(num + "");
        } else {
            goodsNumTF.setText("1");
        }
    }

    @FXML
    private void buyNowClick() {
        if (!(topSpan.getUser() instanceof Buyer)) {
            new Alert(Alert.AlertType.ERROR, "请以买家身份登录！").showAndWait();
            new AppService().closeCurrentTab();
            new AppService().gotoLogin();
        } else {
            List<Item> itemList = new ArrayList();
            itemList.add(getGoodsItemFromUI());
            new ConfirmOrderPane((Buyer) topSpan.getUser(), itemList).showPane();
        }
    }

    @FXML
    private void addToCartClick() {
        if (!(topSpan.getUser() instanceof Buyer)) {
            new Alert(Alert.AlertType.ERROR, "请以买家身份登录！").showAndWait();
            new AppService().closeCurrentTab();
            new AppService().gotoLogin();
        } else {
            new CartService().addToCart((Buyer) topSpan.getUser(), getGoodsItemFromUI());
            new Alert(Alert.AlertType.INFORMATION, "已添加进购物车！").showAndWait();
        }
    }


    private Item getGoodsItemFromUI() {
        Item goodsItem = new Item();
        int amount = Integer.parseInt(goodsNumTF.getText());
        goodsItem.setGoods(goods);
        goodsItem.setAmount(amount);
        goodsItem.setPaymentPrice(goods.getPromotionPrice() * amount);
        goodsItem.setTotalPrice(goods.getPrice() * amount);

        return goodsItem;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setGoodsToUI();
        topSpanContainer.getChildren().add(topSpan);
        String regex = "^[0-9]*$";
        goodsNumTF.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (!newValue.matches(regex)) {
                    goodsNumTF.setText(oldValue);
                }
                if (newValue.equals("")) {
                    goodsNumTF.setText("1");
                }
            }
        });
    }

    private void setGoodsToUI() {
        GoodsPhoto firstPhoto = goods.getGoodsPhotoList().get(0);
        ImageViewUtil.loadImage(mainImageView, firstPhoto.getPhotoUrl());
        imagesHBox.getChildren().clear();
        for (GoodsPhoto goodsPhoto : goods.getGoodsPhotoList()) {
            ImageView imageView = new ImageView();
            imageView.setFitWidth(80);
            imageView.setFitHeight(80);
            ImageViewUtil.loadImage(imageView, goodsPhoto.getPhotoUrl());
            imagesHBox.getChildren().add(imageView);
            imageView.setOnMouseMoved(e -> {
                mainImageView.setImage(imageView.getImage());
            });
        }

        goodsNameLabel.setText(goods.getGoodsName());
        priceLabel.setText("¥" + goods.getPrice());
        promotionalPriceLabel.setText("¥" + goods.getPromotionPrice());
        goodsNumTF.setText("1");
        goodsProfileLabel.setText(goods.getProfile());
        salesLabel.setText(goods.getSales() + "");
        inventoryLabel.setText(goods.getInventory() + "");

        shopNameLabel.setText(shop.getShopName());
        sellerNameLabel.setText(shop.getSeller().getUsername());
        quantityScoreLabel.setText(shop.getQualityScore() + "");
        serviceScoreLabel.setText(shop.getServiceScore() + "");
        deliveryScoreLabel.setText(shop.getDeliveryScore() + "");

    }
}
